<template>
  <div class="login_container">
    <div class="login_box">
      <div class="title">
        <h1>欢迎登陆系统</h1>
      </div>
      <!-- 登录表单区域 -->
      <el-form
        label-width="0px"
        :model="loginForm"
        :rules="loginRules"
        class="login_form"
        ref="loginFormRef"
      >
        <!--        model  表单数据对象   rules 表单验证规则-->

        <!-- 用户名 -->
        <el-form-item prop="name" inline="true">
          <!-- 字体文件在入口文件引入后，可以在 prefix-icon 写class名 -->
          <el-input
            v-model="loginForm.name"
            prefix-icon="iconfont icon-user"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="pwd">
          <el-input
            type="password"
            v-model="loginForm.pwd"
            prefix-icon="iconfont icon-3702mima"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item  class="btns">
          <el-button type="primary" @click="dialogFormVisible = true" class="btnMargin">注册</el-button>
          <!--          注册弹框 -->
          <el-dialog title="请填写注册信息" :visible.sync="dialogFormVisible">
            <el-form :model="registerForm" label-width="100px" :rules="registerRules" ref="registerRef">
              <el-form-item label="用户名" prop="name"  class="register_item">
                <el-input v-model="registerForm.name" placeholder="请输入用户名" prefix-icon="iconfont icon-user"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="pwd" class="register_item">
                <el-input type="password" v-model="registerForm.pwd" placeholder="请输入密码" prefix-icon="iconfont icon-3702mima" show-password></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancelDialogForm">取 消</el-button>
              <el-button type="primary" @click="register">确 定</el-button>
            </div>
          </el-dialog>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button
            type="info"
            @click="resetLoginForm"
            title="重置表单数据、清除验证规则"
          >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
    import { mapState } from 'vuex'

    export default {
        name: "Login",
        data() {
            return {
                // 这是登录表单的数据绑定对象
                loginForm: {
                    name: "",
                    pwd: "",
                },
              registerForm: {
                  name:"",
                  pwd:""
              },
              dialogFormVisible:false,
                // 验证规则
                loginRules: {
                    // 验证用户名是否合法
                    name: [
                        { required: true, message: "请输入用户名", trigger: "blur" },
                        {
                            min: 3,
                            max: 16,
                            message: "用户名长度在 3 到 16 个字符",
                            trigger: "blur",
                        },
                    ],
                    // 验证密码是否合法
                    pwd: [
                        { required: true, message: "请输入登录密码", trigger: "blur" },
                        {
                            min: 5,
                            max: 16,
                            message: "密码长度在 6 到 16 个字符",
                            trigger: "blur",
                        },
                    ],
                },
              registerRules: {
                // 验证用户名是否合法
                name: [
                  { required: true, message: "请输入用户名", trigger: "blur" },
                  {
                    min: 3,
                    max: 16,
                    message: "用户名长度在 3 到 16 个字符",
                    trigger: "blur",
                  },
                ],
                // 验证密码是否合法
                pwd: [
                  { required: true, message: "请输入注册密码", trigger: "blur" },
                  {
                    min: 5,
                    max: 16,
                    message: "密码长度在 6 到 16 个字符",
                    trigger: "blur",
                  },
                ],
              },
                // 消息框
                // notify: null,
            };
        },
        methods: {
            // 点击重置按钮，重置表单数据和验证规则
            resetLoginForm() {
                console.log(this);
                this.$refs.loginFormRef.resetFields();
            //    对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
            },
            login() {
                // 判断是否校验通过 => valid是否通过，field未通过的字段
                this.$refs.loginFormRef.validate(async (valid, field) => {
                    // console.log(valid, field);
                    // 未通过验证
                    if (!valid) {
                    let arr = Object.keys(field);
                    // 拿到未通过验证的验证规则提示
                    return this.$message.error({
                        message: field[arr[0]][0].message,
                        duration: 2000,
                    });
                }

                let { data: result } = await this.$http.post("/user/login", this.loginForm);
                // 登录失败
                if (result.code !== 200) {
                    return this.$message.error({
                      //利用vue的message弹框提示信息
                        message: result.message,
                        duration: 2000,
                    });
                }
                //登录成功
                this.$message.success({
                    //利用vue的message弹框提示信息
                    message: result.message,
                    duration: 2000,
                  });
                // console.log(result);
                // this.$store.commit('setToken',result.data.token);
                // console.log(this.$store.state.userToken)


                // 保存token
                 window.sessionStorage.setItem("token", result.data.token);
                 window.sessionStorage.setItem("identity", result.data.role);
                // this.$store.commit('setToken',result.data.token);
                //  let user = 'user'
                //  this.$store.commit('setIdentity',result.data.role);
                //   this.$store.commit('setPath',this.$route.path);
                 console.log('role:',result.data.role)
                // console.log(this.$store.state.userToken)
                // 跳转到首页
                // this.$router.push("/generalInfo");
                  if(result.data.role==='normal'){
                    this.$router.push("/generalInfo");
                  }else if(result.data.role==='agent'){
                    this.$router.push("/manage");
                  }
                  //刷新
                  this.$router.go(0)
            });
            },
            //弹出框的取消按钮
            cancelDialogForm(){
              this.dialogFormVisible=false;
            },
            register(){
            // 判断是否校验通过 => valid是否通过，field未通过的字段
            this.$refs.registerRef.validate(async (valid, field) => {
              // console.log(valid, field);
              // 未通过验证
              if (!valid) {
                let arr = Object.keys(field);
                // 拿到未通过验证的验证规则提示
                return this.$message.error({
                  message: field[arr[0]][0].message,
                  duration: 2000,
                });
              }

              let { data: result } = await this.$http.post("/user/register", this.registerForm);
              // 登录失败
              if (result.code !== 200) {
                return this.$message.error({
                  //利用vue的message弹框提示信息
                  message: result.message,
                  duration: 2000,
                });
              }
              console.log(result);
              // this.$store.commit('setToken',result.data.token);
              // console.log(this.$store.state.userToken)
              //登录成功
              this.$message.success({
                //利用vue的message弹框提示信息
                message: result.message,
                duration: 2000,
              });
              // 保存token
              // window.sessionStorage.setItem("token", result.data.token);
              // this.$store.commit('setToken',result.data.token);
              // console.log(this.$store.state.userToken)
              // 跳转到首页
              this.dialogFormVisible=false;
            });
          }
        },
      computed:{
        ...mapState([
          'identity'
        ])
      },
      mounted(){
        console.log(this.identity)
        let defaultIndentity = 'default'
        this.$store.commit('resetIdentity',defaultIndentity)
        console.log(this.identity)
      },
      //组件创建之前
      beforeCreate(){
          window.sessionStorage.setItem('identity','default')
      }
    };
</script>

<style lang="less" scoped>
  .login_container {
    height: 100%;
    background-color: #2b4b6b;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 200px;
  }
  .title h1{
    margin-top: 20px;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-family: 华文行楷;
    color: #01699F;
    font-size: 30px;
  }
  .login_box {
    width: 450px;
    height: 300px;
    background: #fff;
    border-radius: 3px;
    position: absolute;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
  }
  .login_form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
  }
  .btns {
    display: flex;
    justify-content: flex-end;
  }
  .btnMargin{
    margin-right: 10px;
  }
  .register_item{
    margin: 40px;
  }
</style>
